package algorithm;

/**
 * 请实现一个函数，将一个字符串中的每个空格替换成“%20”。例如，当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
 * ReplaceSpace
 */
public class ReplaceSpace {


    //遍历替代
    public String replace(String str){
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < str.length(); i++) {
            if (" ".equals( String.valueOf(str.charAt(i)))) {
                sb.append("%20");
            } else {
                sb.append(String.valueOf(str.charAt(i)));
            }
        }
        return sb.toString();
    }

    //使用java API实现
    public String replaceWithAPI(String str){

        return str.toString().replaceAll("\\s", "%20");
    }



    public static void main(String[] args) {
        ReplaceSpace rs = new ReplaceSpace();

        String str = "I'am a boy";
        System.out.println(rs.replace(str));

        String str2 = "She's a girl";
        System.out.println(rs.replaceWithAPI(str2));
    }
}